define(['jquery'], function ($) {

	 $.getUrlParams = function(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
			results = regex.exec(location.search);
		return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	}
	
	var _lk  = 'http://203.0.65.5:8080/ws/ext.jsp?AJBS={0}';
	var _ks  = { 'docs:case' : '案由', 'pages' : '网页' }
	var _vpo = { }
	var _vps = [ 'q', 'k', 'b', 'p', 'v' ];
	for(var _i = 0; _i < _vps.length; _i++) {
		var _k = _vps[_i];
		var _v = $.getUrlParams(_k);
		if(!_v || _v == 'null' || _v == '') {
			// continue;
		} else {
			_vpo[_k] = _v;
		}
	}
	
	var getPageUrl = function( vpo ) {
		vpo = vpo || {};
		if(_vpo) {
			for(var _i = 0; _i < _vps.length; _i++) {
				var _k = _vps[_i];
				if ( '' == vpo[_k]) {
					delete vpo[_k]
				} else if(_vpo[_k] && !vpo[_k]) {
					vpo[_k] = _vpo[_k]
				}
			}
		}
		var arr = [];
		for(_k in vpo) {
			// console.log(vpo);
			arr.push(_k + '=' + vpo[_k])
		}

		
		return '?' +  arr.join('&');
	}

	// console.log(_vpo);


	// do query result 
	var autoSize = function() { }

	if(_vpo && _vpo.q) {

		$('body').addClass('rs');
		
		autoSize = function(){
			var _h = $(window).height();
			$('.sb').height(120);
			$('.sr').height(_h - 50 - 120);
			$('.ft').height(50);
			$('.sr-page').height(_h - 50 - 120 - 20 - 50);
			$('.sr-menu').height(_h - 50 - 120);
			$('.sr-navi').height(50);
		};


		var page = function(data) {
			var nodes = [];
			/*
			var hl = data.highlighting;
			for(var k in hl) {
				var v = hl[k].content;
				console.log(v);
			}
			*/
			var _n = '案件';
			if(_vpo.k && _vpo.k.indexOf('pages') == 0) {
				_n = '网页';
			}
			var cas = data.data;
			var hls = data.highlighting;
			for(var i =0; i < cas.length; i++) {
				var ca = cas[i];
				if(ca['id'] && ca['docid'] && ca['caseid']) {
					var hl = hls[ca['id']]['content'].join('<br />');
					// console.log(ca);
					nodes.push(
						'<dl>' + '<dt><a href="' + _lk.replace('{0}',ca['docid'])  + '" target="_blank">' + _n + ':' +  ca['caseid'] + '</a></dt>'  + '<dd>' + hl + '</dd>' + '</dl>'	
					)
				} else if(ca['id'] && ca['url']) {
					var hl = hls[ca['id']]['content'].join('<br />');
					nodes.push(
						'<dl>' + '<dt><a href="' + ca['url'] + '" target="_blank">' + _n + ':' +  ca['url'] + '</a></dt>'  + '<dd>' + hl + '</dd>' + '</dl>'	
					)
				}
			}
			$('.sr-page').html( '<div>' + nodes.join("\n") + '</div>' );
			// console.log($('.sr-page').html());
		}

		var navi = function(data) {
			// "current_page": 1, "total-docs": 13557, "next_page_number": 2, "end_index": 1356, "has_previous": false, "has_other_pages": true, "previous_page_number": 0, "start_index": 0
			// "has_next": true, "data-number": 10, 
			var x = 10;
			var cur = Math.floor( $.getUrlParams('p') ) || data['current_page'];
			var nodes = [];
			if(data['has_previous']) {
				var u = getPageUrl({'p': data['previous_page_number'] });
				nodes.push('<a href="' + u + '"><span>上一页</span></a>');
			}
			var a = Math.ceil( data['end_index'] / x )
			var b = Math.floor( (cur - 1) / x )
			var s = b * x;
			//if( cur % x > 5) {
			//	s = cur - 4;
			//} 
			for( var c = s; c < (s + x); c++) {
				var p = c + 1;
				var u = getPageUrl({'p': p});
				if( p > data['end_index'] ) {
					break;
				}
				if( (p % x) == (cur % x)  ) {
					nodes.push('<span>' + p + '</span>');
				} else {
					nodes.push('<a href="' + u + '"><span>' + p + '</span></a>');
				}
			}
			// if(data['current_page'] < data['end_index']) {
			if(data['has_next']) {
				var u = getPageUrl({'p': data['next_page_number']});
				nodes.push('<a href="' + u + '"><span>下一页</span></a>');
			}
			$('.sr-navi').html( '<div> ' + nodes.join("\n") + ' <span>统一检索 为您找到' + data['total-docs'] + '条记录</span> </div>' );
		}

		var menu = function(data) {
			var nodes = [];
			var mb = data.facets.main_briefs;
			var b = _vpo.b || null;
			// $.ajax({url: 'briefs.jsp', dataType: 'json'}).done(function(resp){
			$.ajax({url: 'js/app/briefs.js', dataType: 'json'}).done(function(resp){
					// console.log($(resp).values());
				var kbs = [];
				var kbm = {}
				//var n = 0;
				for(var k in resp) {
					var v = $.trim(resp[k]);
					if(kbs.indexOf(v) < 0) {
						kbs.push(v);
						kbm[v] = [];
					}
					if(kbm[v]) kbm[v].push(k);
					//n++;
				}
				//console.log(n);
				//console.log(kbs.length);
				for(var i = 0; i < kbs.length; i++) {
					var kb = kbs[i];
					var ks = kbm[kb];
					var snodes = [];
					for(var j = 0; j < ks.length; j++) {
						var k = ks[j];
						var v = mb[k];
						var u = getPageUrl({'b': k, 'p' : 1});
						if(null == b && v > 0) {
							snodes.push(
								'<li><a href="' + u + '">' + k + ':' + v + '</a></li>'
							)
						} else if (null != b && v > 0 && b == k) {
							snodes.push(
								'<li><a href="' + u + '">' + k + ':' + v + '</a></li>'
							)
						}
					}
					
					if(snodes.length > 0) {
						nodes.push('<ul class="menuitem">' + kb + snodes.join("") + '</ul>')
					}
				}
				/*
				var b = _vpo.b || null;
				for(var k in mb) {
					var v = mb[k];
					var u = getPageUrl({'b': k});
					if(null == b && v > 0) {
						nodes.push(
							'<ul class="menuitem">'	+ k  + '<li><a href="' + u + '">' + k + ':' + v + '</a></li>' + '</ul>'
						)
					} else if (null != b && v > 0 && b == k) {
						nodes.push(
							'<ul class="menuitem">'	+ k  + '<li><a href="' + u + '">' + k + ':' + v + '</a></li>' + '</ul>'
						)
					}
				//	if(v > 0) console.log(k + ', ' + v)
				}
				*/
				//return {
				//	menu: nodes.join("\n")
				//}
				$('.sr-menu').html(  '<h3>共' + data['total-docs'] + '条记录</h3>' + '<div class="scroll menu">' + nodes.join("\n") + '</div>' );
			});
			
			/*
			var b = _vpo.b || null;
			for(var k in mb) {
				var v = mb[k];
				var u = getPageUrl({'b': k});
				if(null == b && v > 0) {
					nodes.push(
						'<ul class="menuitem">'	+ k  + '<li><a href="' + u + '">' + k + ':' + v + '</a></li>' + '</ul>'
					)
				} else if (null != b && v > 0 && b == k) {
					nodes.push(
							'<ul class="menuitem">'	+ k  + '<li><a href="' + u + '">' + k + ':' + v + '</a></li>' + '</ul>'
					)
				}
			//	if(v > 0) console.log(k + ', ' + v)
			}
			//return {
			//	menu: nodes.join("\n")
			//}
			$('.sr-menu').html(  '<h3>共' + data['total-docs'] + '条记录</h3>' + '<div class="scroll menu">' + nodes.join("\n") + '</div>' );
			*/
		}

		$.ajax({ 
			url: 'search.jsp',
            type: "POST",
            dataType: "json", //表示返回值类型，不必须
            // data: JSON.stringify(_vpo),
            data: _vpo
        }).done(function(resp) {

			if(!resp && !resp.facets) return;
			var data = resp;
			// 抱歉，没有找到与“简单”相关的结果!
			if(data && data['total-docs']) {
				$('body').removeClass('em');
				if(_vpo.k && _vpo.k.indexOf('pages') == 0) {
					$('body').addClass('pg');
					// no menu
				} else {
					$('body').removeClass('pg');
					menu(data);
				}
				page(data);
				navi(data);
				if(!_vpo.v || _vpo.b) {
					var u = getPageUrl({'v': 't', 'b' : ''});
					$('.sb .more').attr('href', u).show();
					var left = ( $('.sb input[name=q]').offset().left + $('.nav').width() + $('.sb .submit').width() + $('.sb .more').width() + 18 - 180 )
					$('.nav').css( { 'left': (0 - left) } );
				}
			} else {
				$('body').addClass('em');
				$('.sr-page').html('<h2>' + '抱歉，没有找到与“<em>' + _vpo['q'] + '</em>”相关的结果!' + '</h2>');
			}
        });

		/*
		require( ["app/results"], function (resp) {
			if(!resp.data && !resp.data.facets) return;
			// console.log(resp.data);
			// total-docs
			var data = resp.data;
			// 抱歉，没有找到与“简单”相关的结果!
			if(data && data['total-docs']) {
				$('body').removeClass('em');
				menu(data);
				page(data);
				navi(data);
			} else {
				$('body').addClass('em');
				$('.sr-page').html('<h2>' + '抱歉，没有找到与“<em>' + _vpo['q'] + '</em>”相关的结果!' + '</h2>');
			}
		} );
		*/

	} else {
		$('body').removeClass('rs');
		// require( ["app/index"], function (resp) {
		//
		// } );
		$('.sr').hide();
		autoSize = function(){
			var _h = $(window).height();
			$('.sb').height(_h);
			var left = ( $('.sb input[name=q]').offset().left + $('.nav').width() + $('.sb .submit').width() + 18)
			$('.nav').css( { 'left': (0 - left) } );
		};


	}
	

	$(window).bind("load resize", autoSize);
	(autoSize)();

	var _sub = $('.sb .submit');
	var _nq = $('.sb input[name=q]');
	var _nk = $('.nav .dropdown-toggle span:first');

	_sub.bind('search', function() {
		var nq = _nq;
		if( nq && nq.val() ) {
			// do url query
			// var uri = [ '?q=', nq.val() ].join('');
			var uri = getPageUrl({'q': nq.val(), 'p' : ''});
			window.location.href=uri;
		} else {
			window.location.href='?';
			// todo nothing
		}
		// var uri = [ '?q=',  ]
		// console.log('in search');
	});

	_sub.on('click', function() {
		var e = 'search';
		if( $(this).bind(e) ) {  
			$(this).trigger(e); 
		}
		return false;
	});

	var _form = $('.sb form');
	_form.on('submit', function() {
		var e = 'search';
		if( _sub.bind(e) ) {  
			_sub.trigger(e); 
		}
		return false;
	});

	if(_vpo && _vpo.q) _nq.val(_vpo.q);
	if(_vpo && _vpo.k) _nk.html(_ks[_vpo.k]);

	$('.nav .dropdown-menu li a').each(function() {
		var _k = $(this).attr('href').split(/\#/)[1] || 'docs:case';
		$(this).on('click', function() {
			var u = getPageUrl({'k': _k});
			window.location.href = u;
			return false;
		});
	})


});